package main

import (
	"log"
	"net/http"
	"strconv"

	"gogo"
)

func main() {
	// 初始化数据库连接
	if err := gogo.SQLInit("mysql", "数据库用户名:数据库密码@tcp(数据库地址:数据库端口)/表名?charset=utf8", 10, 1); err != nil {
		log.Fatalf("SQLInit error: %v", err)
	}

	// 增
	gogo.POST("/restful/:tablename", func(ctx *gogo.HTTPContext) {
		affect, err := gogo.SQLInsert(
			ctx.GetPathParam(":tablename"),
			ctx.GetPostBody())

		if err != nil {
			log.Fatalf("SQLInit error: %v", err)
			ctx.WriteString(err.Error())
		} else {
			ctx.WriteString(strconv.FormatInt(affect, 10))
		}
	})

	// 删
	gogo.DELETE("/restful/:tablename/:id", func(ctx *gogo.HTTPContext) {
		affect, err := gogo.SQLDelete(
			ctx.GetPathParam(":tablename"),
			"id="+ctx.GetPathParam(":id"))

		if err != nil {
			log.Fatalf("SQLInit error: %v", err)
			ctx.WriteString(err.Error())
		} else {
			ctx.WriteString(strconv.FormatInt(affect, 10))
		}
	})

	// 改
	gogo.PUT("/restful/:tablename/:id", func(ctx *gogo.HTTPContext) {
		affect, err := gogo.SQLUpdate(
			ctx.GetPathParam(":tablename"),
			"id="+ctx.GetPathParam(":id"),
			ctx.GetPostBody())

		if err != nil {
			log.Fatalf("SQLInit error: %v", err)
			ctx.WriteString(err.Error())
		} else {
			ctx.WriteString(strconv.FormatInt(affect, 10))
		}
	})

	// 查
	gogo.GET("/restful/:tablename/:id", func(ctx *gogo.HTTPContext) {
		queryData, err := gogo.SQLQueryByMap(
			"",
			ctx.GetString("feilds"),
			ctx.GetPathParam(":tablename"),
			"id="+ctx.GetPathParam(":id"),
			"", 0, 1)

		if err != nil {
			log.Fatalf("SQLInit error: %v", err)
			ctx.WriteString(err.Error())
		} else {
			ctx.WriteJSON(queryData)
		}
	})

	// 查
	gogo.GET("/restful/:tablename", func(ctx *gogo.HTTPContext) {
		queryData, err := gogo.SQLQueryByMap(
			ctx.GetString("columnname"),
			ctx.GetString("feilds"),
			ctx.GetPathParam(":tablename"),
			ctx.GetString("where"),
			ctx.GetString("order"),
			ctx.GetInt("offset", 0),
			ctx.GetInt("count", 10))

		if err != nil {
			log.Fatalf("SQLInit error: %v", err)
			ctx.WriteString(err.Error())
		} else {
			ctx.WriteJSON(queryData)
		}
	})

	// 404页面
	gogo.STATUS(http.StatusNotFound, func(ctx *gogo.HTTPContext) {
		ctx.WriteHeaderStatus(http.StatusNotFound)
		ctx.WriteString("Page Not Found !")
	})

	// 启动HTTP服务
	gogo.StartHTTP(3009)
}
